{% extends "base.html" %}

{% block title %}简化版三班制排班 - 长者照护计划系统{% endblock %}

{% block page_title %}简化版三班制排班{% endblock %}

{% block extra_css %}
<style>
    .form-section {
        margin-bottom: 20px;
        padding: 15px;
        border: 1px solid #dee2e6;
        border-radius: 5px;
        background-color: #f8f9fa;
    }
    
    .custom-shift {
        margin-bottom: 10px;
        padding: 10px;
        border: 1px solid #dee2e6;
        border-radius: 5px;
        background-color: #fff;
    }
    
    .result-section {
        margin-top: 20px;
    }
    
    #loading {
        display: none;
        text-align: center;
        margin: 20px 0;
    }
    
    #result {
        display: none;
    }
    
    .time-slot-table {
        font-size: 0.9rem;
    }
    
    .time-slot-table th, .time-slot-table td {
        padding: 0.5rem;
    }
</style>
{% endblock %}

{% block content %}
<div class="row">
    <div class="col-md-12">
        <div class="card">
            <div class="card-header">
                <h5 class="card-title">简化版三班制排班接口说明</h5>
            </div>
            <div class="card-body">
                <p>简化版三班制排班接口是对三班制排班接口的简化版本，支持以下功能：</p>
                <ul>
                    <li>支持使用数字(1,2,3)作为班次名称</li>
                    <li>支持一天分几段（班制数量），可选1、2、3</li>
                    <li>支持自定义各班次的时间范围</li>
                    <li>支持一个小时按多少分钟分段（10-60，默认20分钟）</li>
                </ul>
                <p>接口地址：<code>/simple_three_shift_schedule</code></p>
                <p>请求方法：<code>POST</code></p>
                <p>示例请求：</p>
                <pre class="json-display">
{
  "shift_mode": 3,
  "custom_shifts": [
    {"name": "1", "start_time": "07:00", "end_time": "15:00"},
    {"name": "2", "start_time": "15:00", "end_time": "23:00"},
    {"name": "3", "start_time": "23:00", "end_time": "07:00"}
  ],
  "time_interval_minutes": 20
}
                </pre>
            </div>
        </div>
    </div>
</div>

<div class="row mt-4">
    <div class="col-md-12">
        <div class="card">
            <div class="card-header">
                <h5 class="card-title">生成简化版三班制排班</h5>
            </div>
            <div class="card-body">
                <form id="scheduleForm">
                    <div class="form-section">
                        <h6>班制控制</h6>
                        <div class="row mb-3">
                            <div class="col-md-4">
                                <label for="shift_mode" class="form-label">一天分几段（班制数量）</label>
                                <select class="form-select" id="shift_mode" name="shift_mode">
                                    <option value="1">1段（一班制）</option>
                                    <option value="2">2段（二班制）</option>
                                    <option value="3" selected>3段（三班制）</option>
                                </select>
                            </div>
                            <div class="col-md-4">
                                <label for="time_interval_minutes" class="form-label">一个小时分几段（分钟）</label>
                                <select class="form-select" id="time_interval_minutes" name="time_interval_minutes">
                                    <option value="10">10分钟（6段）</option>
                                    <option value="12">12分钟（5段）</option>
                                    <option value="15">15分钟（4段）</option>
                                    <option value="20" selected>20分钟（3段）</option>
                                    <option value="30">30分钟（2段）</option>
                                    <option value="60">60分钟（1段）</option>
                                </select>
                            </div>
                            <div class="col-md-4">
                                <label for="day_segments" class="form-label">一天分几段</label>
                                <select class="form-select" id="day_segments" name="day_segments">
                                    <option value="1">1段</option>
                                    <option value="2">2段</option>
                                    <option value="3" selected>3段</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    
                    <div class="form-section">
                        <h6>自定义班次时间范围</h6>
                        <div id="customShiftsContainer">
                            <div class="custom-shift" id="shift1">
                                <div class="row">
                                    <div class="col-md-4">
                                        <label for="shift1_name" class="form-label">班次名称</label>
                                        <input type="text" class="form-control" id="shift1_name" name="custom_shifts[0][name]" value="1">
                                    </div>
                                    <div class="col-md-4">
                                        <label for="shift1_start_time" class="form-label">开始时间</label>
                                        <input type="time" class="form-control" id="shift1_start_time" name="custom_shifts[0][start_time]" value="06:00">
                                    </div>
                                    <div class="col-md-4">
                                        <label for="shift1_end_time" class="form-label">结束时间</label>
                                        <input type="time" class="form-control" id="shift1_end_time" name="custom_shifts[0][end_time]" value="14:00">
                                    </div>
                                </div>
                            </div>
                            
                            <div class="custom-shift" id="shift2">
                                <div class="row">
                                    <div class="col-md-4">
                                        <label for="shift2_name" class="form-label">班次名称</label>
                                        <input type="text" class="form-control" id="shift2_name" name="custom_shifts[1][name]" value="2">
                                    </div>
                                    <div class="col-md-4">
                                        <label for="shift2_start_time" class="form-label">开始时间</label>
                                        <input type="time" class="form-control" id="shift2_start_time" name="custom_shifts[1][start_time]" value="14:00">
                                    </div>
                                    <div class="col-md-4">
                                        <label for="shift2_end_time" class="form-label">结束时间</label>
                                        <input type="time" class="form-control" id="shift2_end_time" name="custom_shifts[1][end_time]" value="22:00">
                                    </div>
                                </div>
                            </div>
                            
                            <div class="custom-shift" id="shift3">
                                <div class="row">
                                    <div class="col-md-4">
                                        <label for="shift3_name" class="form-label">班次名称</label>
                                        <input type="text" class="form-control" id="shift3_name" name="custom_shifts[2][name]" value="3">
                                    </div>
                                    <div class="col-md-4">
                                        <label for="shift3_start_time" class="form-label">开始时间</label>
                                        <input type="time" class="form-control" id="shift3_start_time" name="custom_shifts[2][start_time]" value="22:00">
                                    </div>
                                    <div class="col-md-4">
                                        <label for="shift3_end_time" class="form-label">结束时间</label>
                                        <input type="time" class="form-control" id="shift3_end_time" name="custom_shifts[2][end_time]" value="06:00">
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="form-section">
                        <h6>数据限制</h6>
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label for="elder_limit" class="form-label">老人数量限制</label>
                                <input type="number" class="form-control" id="elder_limit" name="elder_limit" value="5" min="1" max="100">
                            </div>
                            <div class="col-md-6">
                                <label for="caregiver_limit" class="form-label">护理员数量限制</label>
                                <input type="number" class="form-control" id="caregiver_limit" name="caregiver_limit" value="10" min="1" max="100">
                            </div>
                        </div>
                    </div>
                    
                    <div class="d-grid gap-2">
                        <button type="submit" class="btn btn-primary">生成排班</button>
                    </div>
                </form>
                
                <div id="loading" class="mt-4">
                    <div class="spinner-border text-primary" role="status">
                        <span class="visually-hidden">加载中...</span>
                    </div>
                    <p>正在生成排班，请稍候...</p>
                </div>
                
                <div id="result" class="result-section mt-4">
                    <div class="alert alert-success" id="successMessage" style="display: none;"></div>
                    <div class="alert alert-danger" id="errorMessage" style="display: none;"></div>
                    
                    <div class="card">
                        <div class="card-header">
                            <h5 class="card-title">排班结果</h5>
                        </div>
                        <div class="card-body">
                            <ul class="nav nav-tabs" id="resultTabs" role="tablist">
                                <li class="nav-item" role="presentation">
                                    <button class="nav-link active" id="summary-tab" data-bs-toggle="tab" data-bs-target="#summary" type="button" role="tab">排班摘要</button>
                                </li>
                                <li class="nav-item" role="presentation">
                                    <button class="nav-link" id="shift-assignments-tab" data-bs-toggle="tab" data-bs-target="#shift-assignments" type="button" role="tab">护理员排班表</button>
                                </li>
                                <li class="nav-item" role="presentation">
                                    <button class="nav-link" id="schedule-results-tab" data-bs-toggle="tab" data-bs-target="#schedule-results" type="button" role="tab">照护计划总表</button>
                                </li>
                                <li class="nav-item" role="presentation">
                                    <button class="nav-link" id="time-slots-tab" data-bs-toggle="tab" data-bs-target="#time-slots" type="button" role="tab">照护计划分表</button>
                                </li>
                            </ul>
                            <div class="tab-content" id="resultTabsContent">
                                <div class="tab-pane fade show active" id="summary" role="tabpanel">
                                    <div class="mt-3">
                                        <h6>排班摘要</h6>
                                        <div id="summaryContent" class="json-display"></div>
                                    </div>
                                </div>
                                <div class="tab-pane fade" id="shift-assignments" role="tabpanel">
                                    <div class="mt-3">
                                        <h6>护理员排班表</h6>
                                        <div class="table-responsive">
                                            <table class="table table-striped table-bordered">
                                                <thead>
                                                    <tr>
                                                        <th>ID</th>
                                                        <th>护理员</th>
                                                        <th>日期</th>
                                                        <th>班次</th>
                                                        <th>开始时间</th>
                                                        <th>结束时间</th>
                                                    </tr>
                                                </thead>
                                                <tbody id="shiftAssignmentsTableBody">
                                                </tbody>
                                            </table>
                                        </div>
                                    </div>
                                </div>
                                <div class="tab-pane fade" id="schedule-results" role="tabpanel">
                                    <div class="mt-3">
                                        <h6>照护计划总表</h6>
                                        <div class="table-responsive">
                                            <table class="table table-striped table-bordered">
                                                <thead>
                                                    <tr>
                                                        <th>ID</th>
                                                        <th>老人</th>
                                                        <th>日期</th>
                                                        <th>批次号</th>
                                                        <th>时间段数量</th>
                                                        <th>操作</th>
                                                    </tr>
                                                </thead>
                                                <tbody id="scheduleResultsTableBody">
                                                </tbody>
                                            </table>
                                        </div>
                                    </div>
                                </div>
                                <div class="tab-pane fade" id="time-slots" role="tabpanel">
                                    <div class="mt-3">
                                        <h6>照护计划分表</h6>
                                        <div class="table-responsive">
                                            <table class="table table-striped table-bordered time-slot-table">
                                                <thead>
                                                    <tr>
                                                        <th>ID</th>
                                                        <th>老人</th>
                                                        <th>时间段</th>
                                                        <th>活动</th>
                                                        <th>护理员</th>
                                                        <th>日期</th>
                                                    </tr>
                                                </thead>
                                                <tbody id="timeSlotsTableBody">
                                                </tbody>
                                            </table>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
    $(document).ready(function() {
        // 根据班制模式显示/隐藏班次
        $('#shift_mode').change(function() {
            const shiftMode = parseInt($(this).val());
            
            // 显示/隐藏班次
            for (let i = 1; i <= 3; i++) {
                if (i <= shiftMode) {
                    $(`#shift${i}`).show();
                } else {
                    $(`#shift${i}`).hide();
                }
            }
        });
        
        // 表单提交
        $('#scheduleForm').submit(function(e) {
            e.preventDefault();
            
            // 显示加载中
            $('#loading').show();
            $('#result').hide();
            $('#successMessage').hide();
            $('#errorMessage').hide();
            
            // 获取表单数据
            const formData = {};
            const formArray = $(this).serializeArray();
            
            // 处理表单数据
            formArray.forEach(function(item) {
                if (item.name.includes('custom_shifts')) {
                    // 处理自定义班次
                    const matches = item.name.match(/custom_shifts\[(\d+)\]\[(\w+)\]/);
                    if (matches) {
                        const index = matches[1];
                        const property = matches[2];
                        
                        if (!formData.custom_shifts) {
                            formData.custom_shifts = [];
                        }
                        
                        if (!formData.custom_shifts[index]) {
                            formData.custom_shifts[index] = {};
                        }
                        
                        formData.custom_shifts[index][property] = item.value;
                    }
                } else {
                    // 处理其他字段
                    formData[item.name] = item.value;
                }
            });
            
            // 处理自定义班次数组
            if (formData.custom_shifts) {
                // 只保留当前班制模式下的班次
                const shiftMode = parseInt(formData.shift_mode);
                formData.custom_shifts = formData.custom_shifts.slice(0, shiftMode);
            }
            
            // 发送请求
            $.ajax({
                url: '/simple_three_shift_schedule',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(formData),
                success: function(response) {
                    $('#loading').hide();
                    $('#result').show();
                    
                    // 显示成功消息
                    $('#successMessage').text('排班生成成功！').show();
                    
                    // 显示排班摘要
                    $('#summaryContent').text(JSON.stringify(response, null, 2));
                    
                    // 清空表格
                    $('#shiftAssignmentsTableBody').empty();
                    $('#scheduleResultsTableBody').empty();
                    $('#timeSlotsTableBody').empty();
                    
                    // 填充护理员排班表
                    if (response.shift_assignments && response.shift_assignments.length > 0) {
                        response.shift_assignments.forEach(function(assignment) {
                            $('#shiftAssignmentsTableBody').append(`
                                <tr>
                                    <td>${assignment.id}</td>
                                    <td>${assignment.caregiver_name}</td>
                                    <td>${assignment.shift_date}</td>
                                    <td>${assignment.shift_type}</td>
                                    <td>${assignment.shift_start_time}</td>
                                    <td>${assignment.shift_end_time}</td>
                                </tr>
                            `);
                        });
                    }
                    
                    // 填充照护计划总表
                    if (response.schedule_results && response.schedule_results.length > 0) {
                        response.schedule_results.forEach(function(result) {
                            $('#scheduleResultsTableBody').append(`
                                <tr>
                                    <td>${result.id}</td>
                                    <td>${result.elder}</td>
                                    <td>${result.schedule_date}</td>
                                    <td>${result.batch_number || '无'}</td>
                                    <td>${result.slots_count || '0'}</td>
                                    <td>
                                        <button class="btn btn-sm btn-info view-schedule-btn" data-id="${result.id}" data-elder="${result.elder}" data-date="${result.schedule_date}">查看</button>
                                    </td>
                                </tr>
                            `);
                        });
                    }
                    
                    // 填充照护计划分表
                    if (response.time_slots && response.time_slots.length > 0) {
                        response.time_slots.forEach(function(slot) {
                            $('#timeSlotsTableBody').append(`
                                <tr>
                                    <td>${slot.id}</td>
                                    <td>${slot.elder}</td>
                                    <td>${slot.time_slot}</td>
                                    <td>${slot.activity}</td>
                                    <td>${slot.caregiver}</td>
                                    <td>${slot.schedule_date}</td>
                                </tr>
                            `);
                        });
                    }
                },
                error: function(xhr, status, error) {
                    $('#loading').hide();
                    $('#result').show();
                    
                    // 显示错误消息
                    let errorMsg = '排班生成失败！';
                    if (xhr.responseJSON && xhr.responseJSON.error) {
                        errorMsg += ' ' + xhr.responseJSON.error;
                    }
                    $('#errorMessage').text(errorMsg).show();
                }
            });
        });
        
        // 查看排班按钮点击事件
        $(document).on('click', '.view-schedule-btn', function() {
            const id = $(this).data('id');
            const elder = $(this).data('elder');
            const date = $(this).data('date');
            
            // 跳转到查看排班页面
            window.open(`/page/view_schedule_page?elder=${elder}&date=${date}`, '_blank');
        });
        
        // 初始化时触发一次班制模式变更事件
        $('#shift_mode').trigger('change');
    });
</script>
{% endblock %}
